<!--生成支付计划-->
<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <ContentBlock>
        <div>
          <!-- 查询条件 -->
          <el-form ref="searchForm" :model="searchForm" label-width="120px" class="search-form" :rules="rules">
            <el-row>
              <el-col :span="6">
                <el-form-item label="做帐期号" prop="aae002">
                  <el-date-picker
                    v-model="searchForm.aae002"
                    value-format="yyyyMM"
                    type="month"
                    placeholder="请输入做帐期号"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="业务类型" prop="aae710">
                  <el-select v-model="searchForm.aae710" placeholder="请选择">
                    <el-option v-for="item in dict.aae710" :key="item.id" :value="item.value" :label="item.label" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="单据号">
                  <el-input v-model="searchForm.aae072" :disabled="false" />
                </el-form-item>
              </el-col>
              <!--              <el-col :span="6">-->
              <!--                <el-form-item label="本地业务类型" prop="bae710">-->
              <!--                  <el-select v-model="searchForm.bae710" placeholder="请选择">-->
              <!--                    <el-option v-for="item in dict.bae710" :key="item.id" :value="item.value" :label="item.label" />-->
              <!--                  </el-select>-->
              <!--                </el-form-item>-->
              <!--              </el-col>-->
              <el-col :span="6">
                <el-form-item label="险种类型" prop="aae140">
                  <el-select v-model="searchForm.aae140" placeholder="请选择">
                    <el-option v-for="item in dict.aae140" :key="item.id" :value="item.value" :label="item.label" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="单位编号" prop="aab001">
                  <unit-rpc ref="unitRpc" style="width: 93%" @unitRpcCallBack="unitRpcCallBack" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="单位名称">
                  <el-input v-model="searchForm.aab004" :disabled="true" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8" class="text-right" style="float: right">
                <el-form-item>
                  <el-button type="primary" @click.native="search">查询</el-button>
                  <el-button @click="reset">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </ContentBlock>
      <!--      <crudOperation :permission="permission" />-->
      <!--表格渲染-->
      <ContentBlock>
        <el-tabs v-model="activeTab" @tab-click="fnTabChange">
          <!-- 第一个 Tab -->
          <el-tab-pane label="未生成单据信息" name="1">
            <el-table
              ref="table"
              v-loading="crud.loading"
              :show-summary="true"
              :summary-method="getSummaries"
              :cell-style="moneyCellStyle"
              :height="crud.data.length > 0 ? 'calc(100vh - 510px)' : undefined"
              :data="crud.data"
              border
              :header-cell-style="{background:'#f5f7fa', color:'#777'}"
              size="small"
              style="width: 100%;"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column type="index" label="序号" width="50" align="center" header-align="center" />
              <el-table-column prop="aaz010" label="当事人编号" width="150" align="center" header-align="center" />
              <el-table-column prop="aae734" label="当事人名称" width="150" align="center" header-align="center" />
              <el-table-column prop="aae140" width="150" label="险种类型" :formatter="formatter" align="center" header-align="center" />
              <el-table-column v-if="isColumnVisible" prop="aad080" width="150" label="套账类型" visible="true" align="center" header-align="center" />
              <el-table-column prop="aae002" label="费款所属期" width="100" align="center" header-align="center" />
              <el-table-column prop="aae719" label="金额" width="150" align="center" header-align="center" :formatter="formatMoney" />
              <el-table-column prop="bae710" label="本地业务类型" :formatter="formatter" width="150" align="center" header-align="center" />
              <el-table-column prop="bad006" label="处理标志" :formatter="formatter" width="120" align="center" header-align="center" />
              <!--              银行信息-->
              <el-table-column prop="aaf200" label="银行行别" width="150" align="center" header-align="center" />
              <el-table-column prop="aaf217" label="地方银行行别" width="150" align="center" header-align="center" />
              <el-table-column prop="aae668" label="银行名称" width="150" align="center" header-align="center" />
              <el-table-column prop="aae009" label="户名" width="150" align="center" header-align="center" />
              <el-table-column prop="aae010" label="银行账号" width="150" align="center" header-align="center" />
              <el-table-column prop="aae072" label="征集流水号" width="200" align="center" header-align="center" />
              <el-table-column v-if="isColumnVisible" prop="baz244" width="150" label="" visible="true" align="center" header-align="center" />
            </el-table>
            <!--分页组件-->
            <pagination />
          </el-tab-pane>
          <el-tab-pane label="已生成单据信息" name="2">
            <el-table
              ref="table"
              v-loading="crud.loading"
              :show-summary="true"
              :summary-method="getSummaries"
              :cell-style="moneyCellStyle"
              :height="crud.data.length > 0 ? 'calc(100vh - 510px)' : undefined"
              :data="crud.data"
              size="small"
              style="width: 100%;"
              @row-dblclick="handleRowDblClick"
            >
              <el-table-column type="index" label="序号" width="100px" align="center" header-align="center" />
              <el-table-column prop="aaz617" label="批次号" width="250px" align="center" header-align="center" />
              <el-table-column prop="aae140" width="250px" label="险种类型" :formatter="formatter" align="center" header-align="center" />
              <el-table-column prop="aae002" label="费款所属期" width="200px" align="center" header-align="center" />
              <el-table-column prop="aae719" label="金额" width="150px" align="center" header-align="center" :formatter="formatMoney" />
              <el-table-column prop="bae710" label="本地业务类型" :formatter="formatter" width="250px" align="center" header-align="center" />
              <el-table-column
                fixed="right"
                label="单据打印"
                align="center"
                header-align="center"
                width="200px"
              >
                <template slot-scope="scope">
                  <el-button type="primary" icon="el-icon-printer" size="mini" @click="billForOne(scope.row)" />
                </template>
              </el-table-column>
            </el-table>
            <!--分页组件-->
            <pagination />
          </el-tab-pane>
        </el-tabs>

        <!--表单组件-->
        <el-dialog :visible.sync="dialogVisible" :before-close="fnClose" title="单据明细" width="1300px">
          <content-block label="单据明细">
            <!--表格渲染-->
            <el-table
              ref="table"
              v-loading="crud.loading"
              :show-summary="true"
              :summary-method="getSummaries"
              stripe
              height="calc(100vh - 510px)"
              :data="crud.data"
              size="small"
              style="width: 100%;"
              border
              :cell-style="moneyCellStyle"
              :header-cell-style="{background:'#f5f7fa', color:'#777'}"
            >
              <el-table-column type="index" label="序号" width="50" align="center" header-align="center" />
              <el-table-column prop="aaz010" label="当事人编号" width="150" align="center" header-align="center" />
              <el-table-column prop="aae734" label="当事人名称" width="150" align="center" header-align="center" />
              <el-table-column prop="aae140" width="150" label="险种类型" :formatter="formatter" align="center" header-align="center" />
              <el-table-column v-if="isColumnVisible" prop="aad080" width="150" label="套账类型" visible="true" align="center" header-align="center" />
              <el-table-column prop="aae002" label="费款所属期" width="100" align="center" header-align="center" />
              <el-table-column prop="aae719" label="金额" width="150" align="center" header-align="center" :formatter="formatMoney" />
              <el-table-column prop="bae710" label="本地业务类型" :formatter="formatter" width="150" align="center" header-align="center" />
              <!--              <el-table-column prop="bad006" label="处理标志" :formatter="formatter" width="120" align="center" header-align="center" />-->
              <!--              银行信息-->
              <el-table-column prop="aaf200" label="银行行别" width="150" align="center" header-align="center" />
              <el-table-column prop="aaf217" label="地方银行行别" width="150" align="center" header-align="center" />
              <el-table-column prop="aae668" label="银行名称" width="150" align="center" header-align="center" />
              <el-table-column prop="aae009" label="户名" width="150" align="center" header-align="center" />
              <el-table-column prop="aae010" label="银行账号" width="150" align="center" header-align="center" />
              <el-table-column prop="aae072" label="征集流水号" width="200" align="center" header-align="center" />
              <el-table-column v-if="isColumnVisible" prop="baz244" width="150" label="" visible="true" align="center" header-align="center" />
            </el-table>
            <pagination />
          </content-block>
          <div slot="footer" class="dialog-footer">
            <el-button type="text" @click="fnClose">取消</el-button>
          </div>
        </el-dialog>
      </ContentBlock>
    </div>
    <bottom-fixed>
      <div>
        <el-button type="primary" :disabled="saveDisabled" @click="save">生成支付计划</el-button>
      </div>
    </bottom-fixed>
  </div>
</template>

<script>
import crudFinanceAd02 from '@/views/ynsb_comm/ad02/financeAd02'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import pagination from '@crud/Pagination'
import UnitRpc from '@/views/ynsb_comm/comm/module/unitRpc'
import ContentBlock from '@/components/labers/contentBlock'
import { Loading } from 'element-ui'
import moment from 'moment'
import commUtil from '@/views/ynsb_comm/comm/util/commUtil'
import bottomFixed from '@/components/labers/bottomFixed'

const defaultForm = { aac001: null, aac002: null, aac003: null, aac004: null, aac005: null, aac006: null, aac327: null, aac058: null, aac007: null, aae013: null }
export default {
  name: 'FinanceAd02',
  components: { ContentBlock, pagination, UnitRpc, bottomFixed },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: '查询单据信息', url: 'api/financeAd02/getBills', idField: 'baz244', sort: 'baz244,desc', crudMethod: { ...crudFinanceAd02 }})
  },
  // 数据字典
  dicts: ['aae140', 'aae710', 'bae710', 'bad006'],
  data() {
    return {
      rules: {
        aae002: [
          { required: true, message: '做账期号', trigger: 'blur' }
        ],
        aae710: [
          { required: true, message: '业务处理类型', trigger: 'blur' }
        ]
        // bae710: [
        //   { required: true, message: '本地业务处理类型', trigger: 'blur' }
        // ]
      },
      searchForm: {
        aab001: '', // 单位编号
        aab004: '', // 单位名称
        aae072: '', // 单据号
        aae710: '6002', // 业务处理类型
        bae710: '60020101', // 本地业务处理类型
        aae002: moment().format('YYYYMM') // 做账期号
      },
      dialogVisible: false, // 控制弹窗的显示与隐藏
      selectedRow: null, // 存储被双击的行数据
      aac001: '', // 个人编号
      flag: false,
      aab001: '', // 单位编号
      selectedRows: [], // 勾选选中的行
      saveDisabled: false, // 保存控制
      activeTab: '1', // tab控制
      queryFlag: false, // 是否执行查询
      isColumnVisible: false // 隐藏列
    }
  },
  methods: {
    moment,
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return this.queryFlag
    },
    unitRpcCallBack(item) {
      this.form.aab001 = item.aab001
      this.form.aab004 = item.aab004
      this.aab001 = item.aab001
      this.searchForm.aab001 = item.aab001
      this.searchForm.aab004 = item.aab004
    },
    moneyCellStyle({ row, column, rowIndex, columnIndex }) {
      // 为所有金额列设置绿色（列索引 3-8 是金额列）
      if (this.activeTab === '1') {
        if (columnIndex >= 6 && columnIndex <= 6) {
          return {
            color: '#07c160', // 微信绿色
            fontWeight: 'bold'
          }
        }
      } else if (this.activeTab === '2' && this.dialogVisible === false) {
        if (columnIndex >= 4 && columnIndex <= 4) {
          return {
            color: '#07c160', // 微信绿色
            fontWeight: 'bold'
          }
        }
      } else {
        if (columnIndex >= 5 && columnIndex <= 5) {
          return {
            color: '#07c160', // 微信绿色
            fontWeight: 'bold'
          }
        }
      }
      return {}
    },
    // 合计行计算方法
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      // 需要求和的列（prop名称）
      const sumColumns = [
        'aae719'
      ]

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        // 检查当前列是否需要求和
        if (sumColumns.includes(column.property)) {
          const values = data.map(item => Number(item[column.property]))
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            return isNaN(value) ? prev : prev + value
          }, 0)
          console.log(this.formatMoney(sums[index]), 'sums[index]')
          sums[index] = (sums[index] != null) ? `￥${(Number(sums[index]).toFixed(2) + '').replace(/(\d{1,3})(?=(\d{3})+(?:$|\.))/g, '$1,')}` : '--'
        } else {
          sums[index] = '--'
        }
      })
      return sums
    },
    formatMoney(row, column, cellValue) {
      const value = (cellValue != null) ? `￥${(Number(cellValue).toFixed(2) + '').replace(/(\d{1,3})(?=(\d{3})+(?:$|\.))/g, '$1,')}` : '--'
      // return {
      //   value,
      //   class: isPositive ? 'money-cell positive' : 'money-cell'
      // }
      return value
    },
    formatter(row, column, cellValue) {
      // 根据 aae140 的值进行转码
      const key = column.property
      const data = this.dict[key]
      console.log(data, 'data')
      if (commUtil.isNull(data)) {
        return cellValue
      }
      const dataList = data.filter(item => item.value === cellValue)
      if (!commUtil.isNull(dataList)) {
        return dataList[0].label
      } else {
        return '城镇职工正常退费'
      }
    },
    // 关闭事件
    fnClose() {
      this.dialogVisible = false
      // 关闭弹窗
      this.crud.params = {
        aae002: this.searchForm.aae002,
        aab001: this.searchForm.aab001,
        aae710: this.searchForm.aae710,
        bae710: this.searchForm.bae710,
        aae072: this.searchForm.aae072,
        aae140: this.searchForm.aae140,
        queryType: '2'
      }
      this.crud.pageChangeHandler(1)
    },
    // 双击行触发的事件
    handleRowDblClick(row) {
      this.crud.data = []
      this.selectedRow = row // 获取双击的行数据
      this.dialogVisible = true // 显示弹窗
      this.crud.params = {
        aaz617: row.aaz617,
        aae002: this.searchForm.aae002,
        aab001: this.searchForm.aab001,
        aae710: this.searchForm.aae710,
        bae710: this.searchForm.bae710,
        aae072: this.searchForm.aae072,
        aae140: this.searchForm.aae140,
        queryType: '3'
      }
      this.crud.pageChangeHandler(1)
    },
    handleSelectionChange(val) {
      this.selectedRows = val
      console.log(val, '选中')
    },
    personRpcCallBack(item) {
      this.form.aac001 = item.aac001
      this.searchForm.aac001 = item.aac001
      this.searchForm.aac003 = item.aac003
    },
    // 保存
    save() {
      const businessList = this.selectedRows
      if (businessList.length === 0) {
        this.$message.error('暂无可提交的数据，请先勾选保存')
        return
      }
      const param = {
        businessList: JSON.stringify(businessList),
        aab001: this.aab001
      }
      // 蒙层
      const loadingInstance = Loading.service({
        fullscreen: true, // 是否全屏
        text: '保存中...', // 加载文本
        background: 'rgba(0, 0, 0, 0.7)' // 蒙层背景颜色
      })
      crudFinanceAd02.toSave({ ...param }).then(res => {
        console.log(res, '保存回调')
        // 手动关闭加载框
        this.saveDisabled = true
        this.$message.success('业务保存成功!')
        this.search()
        // this.$successModel({ complete: true, aae016: '0' })
        loadingInstance.close()
      }).catch(res => {
        this.$message.error(res)
        loadingInstance.close()
      })
    },
    fnTabChange() {
      this.search()
      if (this.activeTab === '2') {
        this.saveDisabled = true
      } else {
        this.saveDisabled = false
      }
    },
    search() {
      console.log('1111')
      this.$refs.searchForm.validate((valid) => {
        if (valid) {
          this.queryFlag = true
          this.crud.params = {
            aae002: this.searchForm.aae002,
            aab001: this.searchForm.aab001,
            aae710: this.searchForm.aae710,
            bae710: this.searchForm.bae710,
            aae072: this.searchForm.aae072,
            aae140: this.searchForm.aae140,
            queryType: this.activeTab
          }
          this.saveDisabled = false
          this.crud.pageChangeHandler(1)
        } else {
          this.queryFlag = false
          console.log('表单验证失败')
          return false
        }
      })
      // 假设查询的数据
      // crudAfinanceAd02.getAc08({ ...this.searchForm }).then(res => {
      //   console.log(res, 'res')
      //   this.crud.data = res.content
      // })
    },
    // 单据打印
    billForOne(row) {
      window.open('http://127.0.0.1:8085/jmreport/view/1114795175933681664?token=123456&tenantId=3&aaz618=' + row.aaz617, '_blank')
    },
    reset() {
      this.searchForm = {
        aae002: '',
        aae710: '',
        bae710: '',
        aab001: '',
        aaz625: '',
        aab004: ''
      }
      this.tableData = [] // 清空表格数据
    },
    queryCallBack() {
      this.dialogVisible = false // 显示弹窗
    },
    // 日期格式转换
    formatDate(row, column, cellValue) {
      // 格式化日期为 YYYY-MM-DD
      if (cellValue !== null && cellValue !== undefined) {
        const date = new Date(cellValue)
        const year = date.getFullYear()
        const month = (date.getMonth() + 1).toString().padStart(2, '0')
        const day = date.getDate().toString().padStart(2, '0')
        return `${year}-${month}-${day}`
      } else {
        return '--'
      }
    }
  }
}
</script>

<style scoped>

</style>
